import React, { Component } from 'react'
import PropTypes from 'prop-types'

import { reqDeleteImg } from '../../api/admin'
import { BASE_IMG_URL } from '../../utils/constant'

import { Upload, Modal, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

export default class PicturesWall extends Component {

  static propTypes = {
    imgs: PropTypes.array
  }

  state = {
    previewVisible: false,
    previewImage: '',
    fileList: [],
  };

  // constructor(props) {
  //   super(props)

  //   let fileList = []

  //   // 如果传入了imgs属性
  //   const { imgs } = this.props
  //   if (imgs && imgs.length > 0) {
  //     fileList = imgs.map((img, index) => ({
  //       uid: -index, // 每个file都有自己唯一的id
  //       name: img, // 图片文件名
  //       status: 'done', // 图片状态: done-已上传, uploading: 正在上传中, removed: 已删除
  //       url: BASE_IMG_URL + img
  //     }))
  //   }

  //   // 初始化状态
  //   this.state = {
  //     previewVisible: false, // 标识是否显示大图预览Modal
  //     previewImage: '', // 大图的url
  //     fileList // 所有已上传图片的数组
  //   }
  // }

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
    });
  };

  handleChange = async ({ file, fileList }) => {
    console.log(file, fileList);
    if (file.status === 'done') {
      const result = file.response
      if (result.status === 0) {
        message.success('图片上传成功')
        const { name, url } = result.data
        file = fileList[fileList.length - 1]
        file.name = name
        file.url = url
      } else {
        message.error('图片上传失败')
      }
    } else if (file.status === 'removed') {
      const result = await reqDeleteImg({ name: file.name })
      if (result.status === 0) {
        message.success('删除图片成功')
      } else {
        message.error('删除图片失败')
      }
    }
    this.setState({ fileList })
  }

  getImgs = () => {
    return this.state.fileList.map(file => file.name)
  }

  UNSAFE_componentWillMount () {
    let fileList = []

    // 如果传入了imgs属性
    const { imgs } = this.props
    if (imgs && imgs.length > 0) {
      fileList = imgs.map((img, index) => ({
        uid: -index, // 每个file都有自己唯一的id
        name: img, // 图片文件名
        status: 'done', // 图片状态: done-已上传, uploading: 正在上传中, removed: 已删除
        url: BASE_IMG_URL + img
      }))
      this.setState({
        fileList
      })
    }
    this.setState({
      fileList: []
    })
  }

  render () {
    const { previewVisible, previewImage, fileList } = this.state;

    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>上传图片</div>
      </div>
    );
    return (
      <>
        <Upload
          accept="image/*"
          action="/manage/img/upload"
          name='image'
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
        >
          {fileList.length >= 5 ? null : uploadButton}
        </Upload>
        <Modal
          visible={previewVisible}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </>
    );
  }
}

